package com.yb.common.config;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.ueditor.ActionEnter;
import com.yb.framework.fastdfs.FastDFSClient;

/**
 * 改写官方jsp页面获取配置信息
 * ueditor官方通过controller.jsp来读取配置文件config.json
 * 该项目前端是集成的是thymeleaf模板引擎，不支持对jsp文件进行解析。
 */
@RestController
@RequestMapping("/ueditor")
public class UeditorConfig {
	
	@Value("${fdfs.serverIp}")
	private String serverIp;
	@Value("${fdfs.serverPort}")
	private String serverPort;
	
	@Autowired
	private FastDFSClient fastDFSClient;
	
	private final Logger logger = LoggerFactory.getLogger(UeditorConfig.class);
	
	@RequestMapping("/config")
	public JSONObject config(HttpServletRequest request, HttpServletResponse response, 
			String action, MultipartFile upfile) throws IOException {
		JSONObject result = new JSONObject();
		switch (action) {
			case "config":
				// 需要配置 ueditor/ueditor.config.js -》serverUrl 
				logger.info("读取配置文件config.json");
				String rootPath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/static/plugins/ueditor/jsp";
				String configPath = "/config.json";
				String exec = new ActionEnter(request, rootPath, configPath).exec();
				return JSON.parseObject(exec);
			case "uploadimage":
				/**
				 * 得到上传文件所对应的各个参数
				 * {
				 *     "state" => "",          //上传状态，上传成功时必须返回"SUCCESS"
				 *     "url" => "",            //返回的地址
				 *     "title" => "",          //新文件名
				 *     "original" => "",       //原始文件名
				 *     "type" => ""            //文件类型
				 *     "size" => "",           //文件大小
				 * }
				 */
				logger.info("图片上传");
				String filePath = fastDFSClient.uploadFile(upfile);
				String fullPath = "http://"+ serverIp +":"+ serverPort + "/" + filePath;
				result.put("state", "SUCCESS");
				result.put("url", fullPath);
				result.put("title", upfile.getOriginalFilename());
				result.put("original", upfile.getOriginalFilename());
				result.put("type", upfile.getContentType());
				result.put("size", upfile.getSize());
			}
		return result;
	}
}
